#include "formdevlog.h"
#include "ui_formdevlog.h"

#include <QCloseEvent>

FormDevLOG::FormDevLOG(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormDevLOG)
{
    ui->setupUi(this);

    createConnection();

    ui->tableWidget->setColumnCount(3);
    ui->tableWidget->setHorizontalHeaderLabels({"故障时间", "系统模式", "故障详情"});

    // 设置表格属性
    ui->tableWidget->verticalScrollBar()->setStyleSheet("width: 20px;");     //垂直滚动条设置宽度20

    // 设置列宽
    ui->tableWidget->setColumnWidth(0, 200);
    ui->tableWidget->setColumnWidth(1, 150);
    ui->tableWidget->setColumnWidth(2, 700);

    ui->tableWidget->setSortingEnabled(false);

    // 连接返回按钮
    connect(ui->backButton, &QPushButton::clicked, this, [this]() {
        emit backRequested();
        this->hide();
    });

    getAllLogInfo();

    this->move(0, 50);
    this->show();
}

FormDevLOG::~FormDevLOG()
{
    //关闭数据库
    QString connectionName = alarm_info_db.connectionName();
    alarm_info_db.close();
    QSqlDatabase::removeDatabase(connectionName);

    delete ui;
}

void FormDevLOG::add_log_slot(QString sys_time, QString sys_mode, QString message)
{
    LOG_INFO_T log_info_temp;
    log_info_temp.sys_time = sys_time;
    log_info_temp.sys_mode = sys_mode;
    log_info_temp.message = message;
    insertLogInfo(log_info_temp);
    addRowToTable(log_info_temp);
}

void FormDevLOG::addRowToTable(const LOG_INFO_T& log_info)
{
    // 如果行数达到500，先移除第一行
    if (ui->tableWidget->rowCount() >= 500)
    {
        ui->tableWidget->removeRow(0);
    }

    ui->tableWidget->setSortingEnabled(false);

    int row = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(row);

    // 设置不同级别的颜色
    QTableWidgetItem *timeItem = new QTableWidgetItem(log_info.sys_time);
    QTableWidgetItem *sysmodeItem = new QTableWidgetItem(log_info.sys_mode);
    QTableWidgetItem *msgItem = new QTableWidgetItem(log_info.message);

    timeItem->setForeground(Qt::white);
    sysmodeItem->setForeground(Qt::yellow);
    msgItem->setForeground(Qt::red);

    ui->tableWidget->setItem(row, 0, timeItem);
    ui->tableWidget->setItem(row, 1, sysmodeItem);
    ui->tableWidget->setItem(row, 2, msgItem);

    ui->tableWidget->setSortingEnabled(true);
    ui->tableWidget->sortByColumn(ui->tableWidget->horizontalHeader()->sortIndicatorSection(), ui->tableWidget->horizontalHeader()->sortIndicatorOrder());


    // 自动滚动到底部
    ui->tableWidget->scrollToBottom();
}

//-----------------------------数据库---------------------------
//创建数据库
bool FormDevLOG::createConnection()
{
    alarm_info_db = QSqlDatabase::addDatabase("QSQLITE", "devlog");
    alarm_info_db.setDatabaseName(DEVLOG_PATH);

    if (!alarm_info_db.open())
    {
        qDebug() << "Dev Log connection fail";
        return false;
    }
    else
    {
        qDebug() << "Dev Log connection ok";
    }

    QSqlQuery query(alarm_info_db);
    QString sql_str = R"(
                CREATE TABLE IF NOT EXISTS ALARM_INFO_TABLE(
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sys_time  VARCHAR(40) NOT NULL,
                sys_mode  VARCHAR(60) NOT NULL,
                alarm_message  VARCHAR(80) NOT NULL);)";

    if (!query.exec(sql_str))
    {
        qDebug() << "ALARM_INFO_TABLE create failed!";
        return false;
    }
    else
    {
        qDebug() << "ALARM_INFO_TABLE create success!";
    }

      // 创建自动维护的触发器
    query.exec("CREATE TRIGGER IF NOT EXISTS maintain_500_rows "
              "AFTER INSERT ON ALARM_INFO_TABLE "
              "BEGIN "
              "DELETE FROM ALARM_INFO_TABLE WHERE id IN ("
              "  SELECT id FROM ALARM_INFO_TABLE "
              "  ORDER BY sys_time ASC "
              "  LIMIT (SELECT MAX(0, COUNT(*) - 500) FROM ALARM_INFO_TABLE)"
              "); "
              "END");

    return true;
}

//删除数据
bool FormDevLOG::deleteLogInfo()
{
    QSqlQuery query(alarm_info_db);
    QString sql_str = QString("delete from ALARM_INFO_TABLE");

    return query.exec(sql_str);
}

//插入数据
bool FormDevLOG::insertLogInfo(const LOG_INFO_T& log_info)
{
    QSqlQuery query(alarm_info_db);
    query.prepare("INSERT INTO ALARM_INFO_TABLE (sys_time, sys_mode, alarm_message) VALUES (:sys_time, :sys_mode, :alarm_message)");
    query.bindValue(":sys_time", log_info.sys_time);
    query.bindValue(":sys_mode", log_info.sys_mode);
    query.bindValue(":alarm_message", log_info.message);
    return query.exec();
}

//查看数据库中的所有数据
void FormDevLOG::getAllLogInfo()
{
    QSqlQuery query("SELECT * FROM ALARM_INFO_TABLE", alarm_info_db);
    while (query.next())
    {
        LOG_INFO_T alarm_info;
        alarm_info.sys_time = query.value(1).toString();
        alarm_info.sys_mode = query.value(2).toString();
        alarm_info.message  = query.value(3).toString();

        addRowToTable(alarm_info);
    }
}

void FormDevLOG::on_pushButton_clicked()
{
    if(deleteLogInfo())
    {
        qDebug() << "delete sql data success!";
    }
    else
    {
        qDebug() << "delete sql data failed!";
    }

    ui->tableWidget->setRowCount(0);
}

void FormDevLOG::closeEvent(QCloseEvent *event)
{
    event->ignore();
    emit backRequested();
    this->hide();
}

